//
//  cartViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/10.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "cartViewController.h"
#import "cartTableViewCell.h"
#import "loginViewController.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "MJRefreshFooter.h"
#import "confirmOrderViewController.h"
#import "AFNetworking.h"
#import "configddd.h"
#import <Masonry/Masonry.h>

@interface cartViewController ()

@end

@implementation cartViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    rightButton.selected = NO;
//    isEditor = NO;
//    [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
 //   [self isLogin];
    if ([PublicFunction getConfigWithKey:@"uid"]) {
        
        //下拉刷新
        self.cartTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self.cartTableView.mj_header endRefreshing];
            [self isLogin];
        }];
       // self.noLoginView.hidden=YES;
    }
    else{
       // self.noLoginView.hidden=NO;
        loginViewController *loginVc =[[loginViewController alloc]init];
        loginVc.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:loginVc animated:YES];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    selected_shop_id = [[NSMutableArray alloc]init];
//    payArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = getColor(@"ffffff");
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selected_shopNotification:) name:@"selected_shop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pay_selected_shopNotification:) name:@"pay_selected_shop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addShopNotification:) name:@"addShop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cart_numNotification:) name:@"cart_num" object:nil];

    [self leftNavHide];
    [self setTitle:@"购物袋"];
    
    rightButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, screenScale(70), screenScale(35))];
    rightButton.titleLabel.font = get4sFont(16);
    [rightButton addTarget:self action:@selector(rightNavItemClick) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    isEditor=NO;
    rightButton.selected = NO;
    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem=rightBarButton;
    
    self.cartTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-49-64-screenScale(79))];
    self.cartTableView.delegate=self;
    self.cartTableView.dataSource=self;
//    self.cartTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
//    self.cartTableView.tableFooterView.userInteractionEnabled = NO;
    self.cartTableView.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    [self.view addSubview:self.cartTableView];
    
    UIView *xView=[[UIView alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-49-64-(1), DEF_SCREEN_WIDTH, (1))];
    xView.backgroundColor=[ZJCModel colorWithString:@"222222"];
    [self.view addSubview:xView];
    
    [self initJiesuanView];
    
//    myLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, (100), DEF_SCREEN_WIDTH, (30))];
//    myLabel.font=[UIFont systemFontOfSize:(18)];
//    myLabel.hidden=YES;
//    myLabel.textAlignment=NSTextAlignmentCenter;
//    myLabel.textColor=DEF_RGB_COLOR(160, 161, 159);
//    myLabel.text=@"抱歉，您的购物车还没有任何商品";
//    [self.view addSubview:myLabel];
}

#pragma mark - request data

- (void)isLogin{
    
    // 登陆判断
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    
    hud.alpha = 0.0;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Is_Login
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       [self requestData];
                                       [hud removeFromSuperview];
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       loginViewController *loginVc =[[loginViewController alloc]init];
                                       loginVc.hidesBottomBarWhenPushed = YES;
                                       
                                       [self.navigationController pushViewController:loginVc animated:YES];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

- (void)requestData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    
    payArray = [[NSMutableArray alloc]init];
    dataArray = [[NSMutableArray alloc]init];
    
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:tokenStr forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Cart_Index
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       dataArray = [[NSMutableArray alloc]init];
                                       dataArray = [returnData objectForKey:@"data"];
                                       
                                       arr = dataArray;
                                       
                                       self.tabBarController.tabBar.items[2].badgeValue = [NSString stringWithFormat:@"%lu",(unsigned long)arr.count];
                                       
                                       if (isEditor) {
                                       
                                           isHejiSelected = NO;
                                           hejiBtn.selected = NO;
                                           selected_shop_id = [[NSMutableArray alloc]init];
                                       }else{
                                       
                                           isisHejiSelected = YES;
                                           hejiBtn1.selected = YES;
                                           
                                       }
                                       payArray = [[NSMutableArray alloc]init];
                                       for (int i = 0; i < arr.count; i ++) {
                                           
                                           NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr[i][@"num"],@"num",arr[i][@"shop_id"],@"shop_id",arr[i][@"price"],@"price", nil];
                                           [payArray addObject:dic];
                                       }
                                       
                                       allPrice = 0.0;
                                       for (int i = 0; i < payArray.count; i ++) {
                                           
                                           allPrice += [payArray[i][@"num"] floatValue] *[payArray[i][@"price"] floatValue];
                                       }
                                       hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
//                                       NSLog(@"\n\n\n\n\n===returnData===%@",returnData);
                                       
                                       [self.cartTableView reloadData];
                                       [self.view reloadInputViews];
                                       
                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       //[PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       self.tabBarController.tabBar.items[2].badgeValue = nil;
                                       allPrice = 0.0;
                                       hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
                                       [self.cartTableView reloadData];
                                       
                                       [hud removeFromSuperview];
                                       
                                   }
                                   else{
                                   
                                       [hud removeFromSuperview];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

#pragma mark - notification

//增加商品数量 更改价格

- (void)addShopNotification:(NSNotification *)text{
    
    allPrice = 0.0;

    if ([text.userInfo[@"selected"]isEqualToString:@"yes"]) {
        
        for (int i = 0; i < payArray.count; i ++) {
            
            if ([payArray[i][@"shop_id"]isEqualToString:text.userInfo[@"shop_id"]]) {
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:payArray[i]];
                [dic setValue:[NSString stringWithFormat:@"%d", [dic[@"num"] intValue] + 1] forKey:@"num"];
                payArray[i] = dic;
                
                //[payArray[i] setValue:[NSString stringWithFormat:@"%d",[payArray[i][@"num"] intValue] + 1] forKey:@"num"];
            }
            
            allPrice += [payArray[i][@"num"] floatValue] *[payArray[i][@"price"] floatValue];
            hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
        }
        
        for (int i = 0; i < arr.count; i ++) {
            
            if ([arr[i][@"shop_id"]isEqualToString:text.userInfo[@"shop_id"]]) {
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:arr[i]];
                [dic setValue:[NSString stringWithFormat:@"%d", [dic[@"num"] intValue] + 1] forKey:@"num"];
                arr[i] = dic;
            }
        }
    }else{
    
        for (int i = 0; i < payArray.count; i ++) {
            
            if ([payArray[i][@"shop_id"]isEqualToString:text.userInfo[@"shop_id"]]) {
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:payArray[i]];
                [dic setValue:[NSString stringWithFormat:@"%d", [dic[@"num"] intValue] - 1] forKey:@"num"];
                payArray[i] = dic;
                
                //[payArray[i] setValue:[NSString stringWithFormat:@"%d",[payArray[i][@"num"] intValue] - 1] forKey:@"num"];
            }
            allPrice += [payArray[i][@"num"] floatValue] *[payArray[i][@"price"] floatValue];
            hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
        }
        
        for (int i = 0; i < arr.count; i ++) {
            
            if ([arr[i][@"shop_id"]isEqualToString:text.userInfo[@"shop_id"]]) {
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:arr[i]];
                [dic setValue:[NSString stringWithFormat:@"%d", [dic[@"num"] intValue] - 1] forKey:@"num"];
                arr[i] = dic;
            }
        }
    }
    
    NSLog(@"=====payArray=====%@",payArray);
}

//选中编辑商品

- (void)selected_shopNotification:(NSNotification *)text{
    
    if ([text.userInfo[@"selected"]isEqualToString:@"yes"]) {
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:text.userInfo[@"shop_id"],@"shop_id",[PublicFunction getConfigWithKey:@"uid"],@"member_id", nil];
        [selected_shop_id addObject:dic];
    }else{
        
        hejiBtn.selected = NO;
        isHejiSelected = NO;
        for (int i = 0 ; i < selected_shop_id.count ; i++) {
            
            if ([text.userInfo[@"shop_id"] isEqualToString: selected_shop_id[i][@"shop_id"]]) {
                
                [selected_shop_id removeObjectAtIndex:i];
            }
        }
    }
    
    NSLog(@"selected_shop_id===%@",selected_shop_id);
}

//选中结算商品

- (void)pay_selected_shopNotification:(NSNotification *)text{
    
    if ([text.userInfo[@"selected"]isEqualToString:@"yes"]) {
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:text.userInfo[@"shop_id"],@"shop_id",text.userInfo[@"num"],@"num",text.userInfo[@"price"],@"price", nil];
        [payArray addObject:dic];
        allPrice += [text.userInfo[@"price"]floatValue] * [text.userInfo[@"num"] floatValue];
        
    }else{
        
        hejiBtn1.selected = NO;
        isisHejiSelected = NO;
        allPrice -= [text.userInfo[@"price"]floatValue] * [text.userInfo[@"num"] floatValue];
        
        for (int i = 0 ; i < payArray.count ; i++) {
            
            if ([text.userInfo[@"shop_id"] isEqualToString: [payArray[i]objectForKey:@"shop_id"]]) {
                
                [payArray removeObjectAtIndex:i];
            }
        }
    }
    
    hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
    
    NSLog(@"payArray===%@",payArray);
}

- (void)cart_numNotification:(NSNotification *)text{

    [self requestData];
}

#pragma mark－－－－－－－initJiesuanView－－－－－－
-(void)initJiesuanView{
    
     //编辑bottom
    
    jiesuanView=[[UIView alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-64-49-(51), DEF_SCREEN_WIDTH, (50))];
    jiesuanView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:jiesuanView];
    [jiesuanView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(80));
    }];
    
    UIView *xxView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, screenScale(1))];
    xxView.backgroundColor=[UIColor lightGrayColor];
    [jiesuanView addSubview:xxView];
    
    UIView *bottomThreadView=[[UIView alloc]initWithFrame:CGRectMake(0, screenScale(79), DEF_SCREEN_WIDTH, screenScale(1))];
    bottomThreadView.backgroundColor=[UIColor lightGrayColor];
    [jiesuanView addSubview:bottomThreadView];
    
    hejiBtn=[[UIButton alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(23), screenScale(35), screenScale(35))];
    isHejiSelected=NO;
    hejiBtn.selected = NO;
    [hejiBtn addTarget:self action:@selector(hejiBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [hejiBtn setImage:[UIImage imageNamed:@"duihao"] forState:UIControlStateSelected];
    [hejiBtn setImage:[UIImage imageNamed:@"circile_b"] forState:UIControlStateNormal];
    [jiesuanView addSubview:hejiBtn];
    
    qxLabel=[[UILabel alloc]initWithFrame:CGRectMake(screenScale(66), screenScale(28), screenScale(70), screenScale(30))];
    qxLabel.text=@"全选";
    qxLabel.font = get4sFont(14);
    [jiesuanView addSubview:qxLabel];
    
//    xxxView=[[UIView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-(241), 0, (1), (49))];
//    xxxView.backgroundColor=[UIColor lightGrayColor];
//    [jiesuanView addSubview:xxxView];
//    xxxView.hidden = YES;
    
//    UIButton *jButton=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-(240), (16.5), (120), (16))];
//    [jButton setTitle:@"加入收藏夹" forState:UIControlStateNormal];
//    [jButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [jButton addTarget:self action:@selector(jButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [jiesuanView addSubview:jButton];
//    jButton.hidden = YES;
    
    UIButton *jiesuanBtn1=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-(120), (1), (120), (49))];
    jiesuanBtn1.backgroundColor=[ZJCModel colorWithString:@"222222"];
    jiesuanBtn1.titleLabel.font = get4sFont(14);
    [jiesuanBtn1 setTitle:@"删除" forState:UIControlStateNormal];
    [jiesuanBtn1 setTitle:@"删除" forState:UIControlStateSelected];
    [jiesuanBtn1 addTarget:self action:@selector(jiesuanBtn1) forControlEvents:UIControlEventTouchUpInside];
    [jiesuanView addSubview:jiesuanBtn1];
    [jiesuanBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(jiesuanView).with.offset(0);
        make.right.mas_equalTo(jiesuanView).with.offset(0);
        make.width.mas_equalTo(screenScale(202));
        make.height.mas_equalTo(screenScale(80));
    }];
    
    //完成bottom
    
    jiesuanView1=[[UIView alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-64-49-(51), DEF_SCREEN_WIDTH, (50))];
    jiesuanView1.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:jiesuanView1];
    [jiesuanView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(80));
    }];
    
    UIView *xxxxView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, screenScale(1))];
    xxxxView.backgroundColor=[UIColor lightGrayColor];
    [jiesuanView1 addSubview:xxxxView];
    
    UIView *bottomThreadView2=[[UIView alloc]initWithFrame:CGRectMake(0, screenScale(79), DEF_SCREEN_WIDTH, screenScale(1))];
    bottomThreadView2.backgroundColor=[UIColor lightGrayColor];
    [jiesuanView1 addSubview:bottomThreadView2];
    
    hejiBtn1=[[UIButton alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(23), screenScale(35), screenScale(35))];
    isisHejiSelected = YES;
    hejiBtn1.selected = YES;
    [hejiBtn1 addTarget:self action:@selector(hejiBtnnClick) forControlEvents:UIControlEventTouchUpInside];
    [hejiBtn1 setImage:[UIImage imageNamed:@"duihao"] forState:UIControlStateSelected];
    [hejiBtn1 setImage:[UIImage imageNamed:@"circile_b"] forState:UIControlStateNormal];
    [jiesuanView1 addSubview:hejiBtn1];
    
    qxLabel1=[[UILabel alloc]initWithFrame:CGRectMake(screenScale(66), screenScale(28), screenScale(70), screenScale(30))];
    qxLabel1.font = get4sFont(14);
    qxLabel1.text=@"全选";
    [jiesuanView1 addSubview:qxLabel1];
    
    hejieLable=[[UILabel alloc]init];
    hejieLable.textColor=[UIColor redColor];
    hejieLable.font = get4sFont(14);
    hejieLable.textAlignment = NSTextAlignmentRight;
    [jiesuanView1 addSubview:hejieLable];
    [hejieLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(jiesuanView1).with.offset(screenScale(15));
        make.right.mas_equalTo(jiesuanView1).with.offset(screenScale(-217));
        
        make.height.mas_equalTo(screenScale(28));
    }];
    
    yLabel=[[UILabel alloc]init];
    yLabel.text=@"不含邮费";
    //    yLabel.hidden=YES;
    yLabel.textAlignment=NSTextAlignmentRight;
    yLabel.textColor=[UIColor grayColor];
    yLabel.font = get4sFont(11);
    [jiesuanView1 addSubview:yLabel];
    [yLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(jiesuanView1).with.offset(screenScale(50));
        make.right.mas_equalTo(jiesuanView1).with.offset(screenScale(-217));
        
        make.height.mas_equalTo(screenScale(24));
    }];

    
    UIButton *jiesuanBtn=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-(120), (1), (120), (49))];
    jiesuanBtn.backgroundColor=[ZJCModel colorWithString:@"222222"];
    jiesuanBtn.titleLabel.font = get4sFont(14);
    [jiesuanBtn setTitle:@"结算" forState:UIControlStateNormal];
    [jiesuanBtn setTitle:@"结算" forState:UIControlStateSelected];
    [jiesuanBtn addTarget:self action:@selector(jiesuanBtn) forControlEvents:UIControlEventTouchUpInside];
    [jiesuanView1 addSubview:jiesuanBtn];
    [jiesuanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(jiesuanView1).with.offset(0);
        make.right.mas_equalTo(jiesuanView1).with.offset(0);
        make.width.mas_equalTo(screenScale(202));
        make.height.mas_equalTo(screenScale(80));
    }];
    
    // 购物车为空时覆盖底部VIEW
    View = [[UIView alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-64-49-(51), DEF_SCREEN_WIDTH, (51))];
    View.backgroundColor = getColor(@"f5f5f5");
    [self.view addSubview:View];
    
}

#pragma mark --- click

//编辑状态下

-(void)hejiBtnClick{
    
    selected_shop_id = [[NSMutableArray alloc]init];
    if (isHejiSelected) {
        
        hejiBtn.selected = NO;
        isHejiSelected=NO;
        [self.cartTableView reloadData];
    }else{
        
        hejiBtn.selected = YES;
        isHejiSelected=YES;
        
        for (int i=0; i<dataArray.count; i++) {
            
            NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:[dataArray[i]objectForKey:@"member_id"],@"member_id",[dataArray[i]objectForKey:@"shop_id"],@"shop_id", nil];
            
            [selected_shop_id addObject:dict];
        }
        [self.cartTableView reloadData];
    }
    NSLog(@"selected_shop_id=====%@",selected_shop_id);
}

//非编辑状态下

-(void)hejiBtnnClick{
    
    payArray = [[NSMutableArray alloc]init];
    if (isisHejiSelected) {
        
        allPrice = 0.0;
        hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
        
        hejiBtn1.selected = NO;
        isisHejiSelected=NO;
        [self.cartTableView reloadData];
    }else{
        
        hejiBtn1.selected = YES;
        isisHejiSelected=YES;

        for (int i=0; i<dataArray.count; i++) {
            
            NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:[dataArray[i]objectForKey:@"num"],@"num",[dataArray[i]objectForKey:@"price"],@"price",[dataArray[i]objectForKey:@"shop_id"],@"shop_id", nil];
            
            [payArray addObject:dict];
        }
        
        allPrice = 0.0;
        for (int i = 0; i < payArray.count; i ++) {
            
            allPrice += [payArray[i][@"num"] floatValue] *[payArray[i][@"price"] floatValue];
        }
        hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
        
        [self.cartTableView reloadData];
    }
    NSLog(@"payArray======%@",payArray);
}

-(void)jiesuanBtn1{
    NSLog(@"删除");
    
    if (selected_shop_id.count < 1) {
        
        [PublicFunction showAlert:nil message:@"还没有选中商品呦" duration:5.0f];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:selected_shop_id, @"data", nil];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue:jsonString forKey:@"data"];
    
    [[MNetworkHandler sharedInstance]conURL:Cart_Shop_Delete
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       [hud removeFromSuperview];
                                       [self requestData];
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

-(void)jiesuanBtn{
    NSLog(@"去结算");
    
    if (payArray.count < 1) {
        
        [PublicFunction showAlert:nil message:@"还没有选中商品呦" duration:10.0f];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:payArray,@"data", nil];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    
    [productParams setValue:tokenStr forKey:@"token"];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:jsonString forKey:@"data"];
    
    /*AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://lmq.quyum.cn/Home/Order/editShopcart" parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setHTTPBody:[productParams dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"Reply JSON: %@ %@", responseObject,responseObject);
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                //blah blah
            }
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        }
    }] resume];*/
    
    NSLog(@"=====mustr==========%@",jsonString);
    NSLog(@"=====productParams==========%@",productParams);
    
    [[MNetworkHandler sharedInstance]conURL:Edit_Shopcart
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       [hud removeFromSuperview];
                                       
                                       confirmOrderViewController *confirmOrderController = [[confirmOrderViewController alloc]init];
                                       confirmOrderController.hidesBottomBarWhenPushed = YES;
                                       [self.navigationController pushViewController:confirmOrderController animated:YES];
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }else if ([returnData[@"code"] intValue] == -2){
                                   
                                       [hud removeFromSuperview];
                                       [PublicFunction showAlert:nil message:returnData[@"msg"] duration:99.9f];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

-(void)jButtonClick{
    NSLog(@"加入收藏夹");
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:@"1" forKey:@"type"];
    
    [[MNetworkHandler sharedInstance]conURL:Cart_Add_Shop_Num
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
    
}

-(void)rightNavItemClick{
    
    if (isEditor) {
        
        isEditor = NO;
        
        NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"no",@"edit",nil];
        NSNotification *notification =[NSNotification notificationWithName:@"edit" object:nil userInfo:dict];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
        [self.cartTableView reloadData];
        [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
        jiesuanView.hidden=YES;
        hejiBtn.hidden=NO;
        qxLabel.hidden=NO;
        jiesuanView1.hidden=NO;
        
        allPrice = 0.0;
        for (int i = 0; i < payArray.count; i ++) {
            
            allPrice += [payArray[i][@"num"] floatValue] *[payArray[i][@"price"] floatValue];
        }
        hejieLable.text = [@"¥" stringByAppendingString:[NSString stringWithFormat:@"%.2f", allPrice]];
        
    }else{
        
        isEditor = YES;
        
        NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"edit",nil];
        NSNotification *notification =[NSNotification notificationWithName:@"edit" object:nil userInfo:dict];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
        [self.cartTableView reloadData];
        [rightButton setTitle:@"完成" forState:UIControlStateNormal];
        jiesuanView.hidden=NO;
        hejiBtn.hidden=NO;
        qxLabel.hidden=NO;
        jiesuanView1.hidden=YES;
        
    }
}

- (void)cartbtnClick{

    [self.tabBarController setSelectedIndex:0];
    [self.navigationController popToRootViewControllerAnimated:NO];
}

#pragma mark  －－－－－－－－－tableView－－－－－－－－－－－－

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cartTableViewCell *cell=(cartTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"cartTableViewCell"];
    
    if (cell == nil) {
        cell=[[cartTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cartTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.myViewController=self;
    
    if (isEditor) {
        
        if (hejiBtn.selected) {
            
            cell.selectBtn.selected = YES;
        }else{
            
            cell.selectBtn.selected = NO;
        }
    }else{
    
        if (hejiBtn1.selected) {
            
            cell.selectBtn.selected = YES;
        }else{
            
            cell.selectBtn.selected = NO;
        }

    }
    
    NSMutableDictionary *dict = arr[indexPath.row];
    
    NSString *urlWare=[dict objectForKey:@"shoppic"];
    NSString *urlN=manage(AP_HOST, urlWare);
    
    NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *urlW=[NSURL URLWithString:strUrl];
    [cell.imageShowView sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
    
//    cell.imageShowView.image = [UIImage imageNamed:[dict objectForKey:@"shoppic"]];
    cell.nameLable.text=[dict objectForKey:@"shop_name"];
    cell.priceLable.text=[dict objectForKey:@"price"];
    
    cell.shop_id = [dict objectForKey:@"shop_id"];
    cell.shop_num = [dict objectForKey:@"num"];
    
    cell.arr = [NSArray arrayWithObjects:[dict objectForKey:@"shop_id"],[dict objectForKey:@"num"],[dict objectForKey:@"price"], nil];
    
    if (!isEditor) {
        
        if (payArray.count > 0) {
            
            for (int i = 0 ; i < payArray.count ; i ++) {
                
                if ([payArray[i][@"shop_id"] isEqualToString:dict[@"shop_id"]]) {
                    
                    cell.selectBtn.selected = YES;
                }
            }
        }
    }else{
    
        if (selected_shop_id.count > 0) {
            
            for (int i = 0 ; i < selected_shop_id.count ; i ++) {
                
                if ([selected_shop_id[i][@"shop_id"] isEqualToString:dict[@"shop_id"]]) {
                    
                    cell.selectBtn.selected = YES;
                }
            }
        }
    }
    
    return cell;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return screenScale(185);
}

//自定义section的尾部
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (dataArray.count < 1) {
        
        UIView *xView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-49-64)];
        xView.backgroundColor = getColor(@"f5f5f5");
        
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake((scrWidth() - screenScale(144))/2,screenScale(300), screenScale(144), screenScale(144))];
        imgView.image = [UIImage imageNamed:@"gouwudatu"];
        [xView addSubview:imgView];
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, screenScale(300 + 164), scrWidth(), screenScale(40))];
        lable.text = @"购物车还没有商品呦";
        lable.textColor = [UIColor grayColor];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.font = get4sFont(14);
        [xView addSubview:lable];
        
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((scrWidth() - screenScale(150))/2, screenScale(300 + 164 + 60), screenScale(150), screenScale(40))];
//        btn.titleLabel.font = get4sFont(14);
//        [btn setTitle:@"去逛逛吧" forState:UIControlStateNormal];
//        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(cartbtnClick) forControlEvents:UIControlEventTouchUpInside];
        [xView addSubview:btn];
        
        UILabel *goShopLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screenScale(150), screenScale(40))];
        goShopLable.font = get4sFont(14);
        goShopLable.textColor = [UIColor grayColor];
        // 下划线
        NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"去逛逛吧～" attributes:attribtDic];
        goShopLable.attributedText = attribtStr;
        [btn addSubview:goShopLable];
        
        View.hidden = NO;
        
        return xView;
    }
    
    UIView *xView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (30))];
    UILabel *bLabel=[[UILabel alloc]initWithFrame:CGRectMake((10), (9), DEF_SCREEN_WIDTH-(20), (12))];
    bLabel.text=@"";
    bLabel.font=[UIFont systemFontOfSize:(12)];
    [xView addSubview:bLabel];
    
    View.hidden = YES;
    
    return xView;
}
//自定义section尾部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (dataArray.count < 1) {
        
        return DEF_SCREEN_HEIGHT -64-49;
    }
    
    return (30);
}


//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    
//    if(indexPath.row==1){
//        return;
//    }
//    
//}

//-(void)rightCartNavItemClick{
//    NSLog(@"点击编辑");
//    if (!isEditor) {
//        isEditor=YES;
//        [self.cartTableView reloadData];
//        [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
//    }else{
//        isEditor=NO;
//        [self.cartTableView reloadData];
//        [rightButton setTitle:@"完成" forState:UIControlStateNormal];
//    }
//}

@end
